source("https://gitee.com/ry2an/my_public_functions_r/raw/master/get_week_by_date.R")
# source("https://gitee.com/ry2an/my_public_functions_r/raw/master/replace_vector_na.R")
library(plyr)
library(ggplot2)


commit_plot <- function(
  end_date = "2021-11-23",
  commits_df = data.frame((as.Date(end_date) - 380) : (as.Date(end_date) + 20), 
                          round(rnorm(n = length((as.Date(end_date) - 380) : 
                                                   (as.Date(end_date) + 20)), 
                                      mean = 20, sd = 5), 0)),
  commit_name = "commits_num",
  file_path = getwd(),
  save = T,
  title = "",
  file_name = paste(title, "_commit.png", sep = ""),
  color_low = "#E0FFFF",
  color_high = "#2F4F4F",
  color_na = "grey50"
){
  names(commits_df) <- c("dates", "commits")
  end_date <- as.Date(end_date)
  start_date <-  end_date - 366
  head_date <- start_date + 1 - get_week_by_date(date = start_date, eng = F)
  tail_date <- end_date + 7 - get_week_by_date(date = end_date, eng = F)
  
  week_num <- (as.numeric(tail_date - head_date) + 1)/7
  
  plot_dates <- head_date : tail_date
  plot_weeks <- rep(1:week_num, each = 7)
  plot_days <- rep((8 - 1:7), week_num)
  plot_df <- data.frame(plot_dates, plot_weeks, plot_days)
  names(plot_df) <- c("dates", "week", "day")
  plot_df <- join(plot_df, commits_df, by = "dates", type = "left")
  # plot_df$commits <- replace_vector_na(x = plot_df$commits, replacement = 0)
  
  plot_df$num_date <- as.Date(plot_df$dates, origin = as.Date("1970-01-01"))
  plot_df$day_eng <- factor(plot_df$day)
  levels(plot_df$day_eng) <- c("Sun", "Sat", "Fri", "Thu", "Wed", "Tue", "Mon")
  plot_df$week_date <- as.Date(plot_df$dates - (8 - plot_df$day) + 1, origin = as.Date("1970-01-01"))
  # head(plot_df, 17)

  # seq_from <- round(min(plot_df$commits, na.rm = T)/5, 0) * 5
  # seq_to <- round(max(plot_df$commits, na.rm = T)/5, 0)*5
  plot <- ggplot(plot_df, aes(x = week_date, y = day_eng, color = commits)) + 
    geom_point(size = 3, shape = 15) +
    scale_color_gradient(low = color_low, high = color_high, na.value = color_na,
                         breaks= seq(from = 0, # can have some bad plot when using seq_from
                                     to = 20, # can have some bad plot when using seq_to
                                     by = 1))+
    theme(axis.title.x=element_blank(), axis.title.y=element_blank(),
          panel.background = element_rect(fill = "white")) +
    guides(color=guide_legend(title=commit_name)) +
    ggtitle(title)
  # setwd(file_path)
  if(save){
    ggsave(filename = paste(file_path, "/",file_name, sep =""), 
           plot = plot, width = 30, height = 5, units = "cm", dpi = 500)
  }
  return(plot)
}


#### TEst Area ####

# setwd("D:\\ruoyanhan18537182018\\hch_trial\\temp\\commit_plot_temp")
# commit_plot(title = "sometitle")

